﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using Intorise.API;
using System.Threading;
using ImageTools;

namespace IntoriseTools
{
    public partial class Form1 : Form
    {
        Bitmap beginImage = null;
        string beginFileName = null;
        bool mouseDown = false;
        Graphics g = null;
        Point beginPoint;
        Rectangle lastRectangle;
        Pen rangePen;
        WindowEventArgs captureHandle = null;
        Size formSize;
        CaptureMode captureMode = CaptureMode.Mode0;
        List<ToolStripMenuItem> menus = new List<ToolStripMenuItem>();

        public Form1()
        {
            InitializeComponent();
            rangePen = new Pen(Color.LightGreen, 1);
            rangePen.DashStyle = DashStyle.Dot;
            formSize = this.Size;
            Form.CheckForIllegalCrossThreadCalls = false;
            this.pictureBox1.MouseDown += this.pictureBox1_MouseDown;
            this.pictureBox1.MouseMove += this.pictureBox1_MouseMove;
            this.pictureBox1.MouseUp += this.pictureBox1_MouseUp;
            menus.Add(this.模式0ToolStripMenuItem);
            menus.Add(this.模式1ToolStripMenuItem);
            menus.Add(this.模式2ToolStripMenuItem);
            menus.Add(this.全屏幕ToolStripMenuItem);
        }

        private void 打开ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    beginFileName = this.openFileDialog1.FileName;
                    Bitmap bitmap = (Bitmap)Bitmap.FromFile(beginFileName);
                    this.pictureBox1.Image = bitmap;
                    if (beginImage != null)
                    {
                        beginImage.Dispose();
                    }
                    beginImage = (Bitmap)bitmap.Clone();
                    this.panel1.AutoScrollMinSize = new Size(bitmap.Width, bitmap.Height);
                    this.panel1.Update();
                    Message("打开图片：" + beginFileName);
                    Message("宽度：" + bitmap.Width + " , 高度：" + bitmap.Height + " , 类型：" + bitmap.PixelFormat);
                }
                catch (Exception ex)
                {
                    Message("打开图片出现错误：" + ex.Message);
                }
            }
        }

        private void Message(string text)
        {
            if (this.richTextBox1.Text.Length > 32767)
            {
                this.richTextBox1.Text = this.richTextBox1.Text.Remove(0, 10000);
            }
            this.richTextBox1.AppendText("\r\n" + text);
        }

        private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
        {
            if (this.pictureBox1.Image == null) { return; }
            mouseDown = true;
            beginPoint = new Point(e.X, e.Y);
        }

        private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
        {
            if (this.pictureBox1.Image == null) { return; }
            if (mouseDown)
            {
                mouseDown = false;
                if (beginPoint.X == lastRectangle.X && beginPoint.Y == lastRectangle.Y)
                {
                    if (lastRectangle.Width > 0 && lastRectangle.Height > 0)
                    {
                        Message("选择范围：x : " + lastRectangle.X + " , y : " + lastRectangle.Y + " , width : " + lastRectangle.Width + " , height : " + lastRectangle.Height);
                    }
                }
                else
                {
                    if (e.X < beginImage.Width && e.Y < beginImage.Height)
                    {
                        Message(string.Format("x : {0} , y : {1} , color : {2}", e.X, e.Y, Intorise.Common.ImageTools.GetPixel(beginImage, e.X, e.Y)));
                    }
                }
            }
        }

        private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
        {
            if (this.pictureBox1.Image == null) { return; }
            if (mouseDown)
            {
                this.pictureBox1.Image = (Image)beginImage.Clone(); ;
                g = Graphics.FromImage(this.pictureBox1.Image);


                lastRectangle = new Rectangle(beginPoint.X, beginPoint.Y, e.X - beginPoint.X, e.Y - beginPoint.Y);

                g.DrawRectangle(rangePen, lastRectangle);
                this.pictureBox1.Update();
            }
        }

        private void 选择范围另存为ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!lastRectangle.IsEmpty)
            {
                if (this.saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    Bitmap newMap = (Bitmap)beginImage.Clone(lastRectangle, beginImage.PixelFormat);
                    newMap.Save(this.saveFileDialog1.FileName, ImageFormat.Bmp);
                }
            }
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {

        }

        private void 退出ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void 保存ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (beginImage != null && this.saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                beginImage.Save(this.saveFileDialog1.FileName, ImageFormat.Bmp);
            }
        }

        private void 从窗口抓图ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            captureHandle = null;
            Message("从窗口抓图：请保持本窗口激活，并将鼠标指向要抓图的窗口，然后按F12键");
            this.TopMost = true;
            formSize = this.Size;
            this.Size = new Size(300, 100);
            this.Update();
            this.WindowState = FormWindowState.Normal;
        }

        private void Form1_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode != Keys.F12) { return; }

            try
            {
                if (captureHandle == null)
                {
                    Point point = new Point();
                    if (!Windows.GetCursorPos(ref point))
                    {
                        Message("获取当前鼠标位置失败，请重试！");
                        return;
                    }
                    IntPtr handle = Windows.WindowFromPoint(point);
                    captureHandle = Helper.GetWinArgs(handle);
                    Message(string.Format("截图窗口句柄为：{0} , 标题：{1} , 位置：x= {2} , y= {3} , 宽度：{4} , 高度：{5}",
                        captureHandle.Hwnd, captureHandle.Title, captureHandle.Location.X, captureHandle.Location.Y,
                        captureHandle.Size.Width, captureHandle.Size.Height));
                }

                if (beginImage != null) { beginImage.Dispose(); }
                switch (captureMode)
                {
                    case CaptureMode.Mode0:
                        beginImage = Helper.CaptureWindow(captureHandle.Hwnd);
                        break;
                    case CaptureMode.Mode1:
                        beginImage = Helper.CaptureWindow0(captureHandle.Hwnd);
                        break;
                    case CaptureMode.Mode2:
                        beginImage = Helper.CaptureWindow1(captureHandle.Hwnd);
                        break;
                    case CaptureMode.Screencopy:
                        beginImage = Helper.CaptureScreen();
                        break;
                }
                if (this.pictureBox1.Image != null)
                {
                    this.pictureBox1.Image.Dispose();
                }
                this.pictureBox1.Image = (Image)beginImage.Clone();
                this.panel1.AutoScrollMinSize = new Size(beginImage.Width, beginImage.Height);
                this.panel1.Update();
                Message("截取窗口 " + captureHandle.Hwnd + "的图像");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                this.TopMost = false;
                this.Size = formSize;
            }
        }

        protected override void WndProc(ref Message m)
        {
            base.WndProc(ref m);
            Message n = new System.Windows.Forms.Message();
            //Message(string.Format("MSG: {0} , WParam: {1} , LParam: {2}", m.Msg, m.WParam, m.LParam));
        }

        private void 模式ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (ToolStripMenuItem item in menus)
            {
                if (sender == item)
                {
                    item.Checked = true;
                    switch (item.Tag.ToString())
                    {
                        case "模式0":
                            captureMode = CaptureMode.Mode0;
                            break;
                        case "模式1":
                            captureMode = CaptureMode.Mode0;
                            break;
                        case "模式2":
                            captureMode = CaptureMode.Mode0;
                            break;
                        case "全屏幕":
                            captureMode = CaptureMode.Screencopy;
                            break;
                    }
                }
                else
                {
                    item.Checked = false;
                }
            }
        }

        private void 清屏ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var image = this.pictureBox1.Image;
            g = Graphics.FromImage(image);
            Brush brushes = Brushes.Black;

            uint c = 0x0000ff00;
            uint d = 0xff000000;
            Color color = Color.FromArgb((int)(d | c));
            //Color color = Color.FromArgb((int)c);

            g.Clear(color);

            this.pictureBox1.Image = null;
            this.pictureBox1.Image = image;
            g.Dispose();
        }
    }
}
